<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<!DOCTYPE html>
<html>
<head>
    <title>公告管理 - 管理后台</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="icon" type="image/x-icon" href="${pageContext.request.contextPath}/logo/favicon.ico">
    <link href="${pageContext.request.contextPath}/css/bootstrap.min.css" rel="stylesheet">
    <style>
        .sidebar {
            min-height: calc(100vh - 56px);
        }
        .table-dark {
            background-color: #212529;
        }
        .table-dark:hover {
            background-color: #2c3034;
        }
    </style>
</head>
<body>
    <jsp:include page="../common/header.jsp"/>
    
    <div class="container-fluid">
        <div class="row">
            <jsp:include page="../common/sidebar.jsp"/>
            
            <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
                <div class="pt-3">
                    <h1 class="h2 mb-3">公告管理</h1>
                    
                    <c:if test="${error != null}">
                        <div class="alert alert-danger alert-dismissible fade show" role="alert">
                            ${error}
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    </c:if>
                    
                    <!-- 查询表单 -->
                    <div class="card mb-3">
                        <div class="card-body">
                            <form action="${pageContext.request.contextPath}/admin/announcement" method="get" class="row g-3">
                                <div class="col-md-3">
                                    <label class="form-label">标题</label>
                                    <input type="text" class="form-control" name="title" placeholder="输入标题关键词..." value="${title}">
                                </div>
                                <div class="col-md-3">
                                    <label class="form-label">内容</label>
                                    <input type="text" class="form-control" name="content" placeholder="输入内容关键词..." value="${content}">
                                </div>
                                <div class="col-md-3">
                                    <label class="form-label">类型</label>
                                    <select class="form-select" name="type">
                                        <option value="">全部</option>
                                        <option value="0" ${type == '0' ? 'selected' : ''}>用户公告</option>
                                        <option value="1" ${type == '1' ? 'selected' : ''}>商家公告</option>
                                    </select>
                                </div>
                                <div class="col-md-3">
                                    <label class="form-label">&nbsp;</label>
                                    <div>
                                        <button type="submit" class="btn btn-dark w-100">查询</button>
                                    </div>
                                </div>
                                <div class="col-md-12">
                                    <a href="${pageContext.request.contextPath}/admin/announcement" class="btn btn-outline-secondary">重置</a>
                                    <button type="button" class="btn btn-primary" onclick="openAddModal()">添加公告</button>
                                </div>
                            </form>
                        </div>
                    </div>
                    
                    <!-- 公告表格 -->
                    <div class="card">
                        <div class="card-body">
                            <div class="mb-3">
                                <button type="button" class="btn btn-danger" id="batchDeleteBtn" onclick="batchDelete()" disabled>批量删除</button>
                                <span class="ms-2 text-muted">已选择 <span id="selectedCount">0</span> 项</span>
                            </div>
                            <div class="table-responsive">
                                <table class="table table-hover">
                                    <thead class="table-dark">
                                        <tr>
                                            <th width="50">
                                                <input type="checkbox" id="selectAll" onchange="toggleSelectAll()">
                                            </th>
                                            <th>ID</th>
                                            <th>标题</th>
                                            <th>内容</th>
                                            <th>类型</th>
                                            <th>状态</th>
                                            <th>创建时间</th>
                                            <th>更新时间</th>
                                            <th>操作</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <c:choose>
                                            <c:when test="${announcements != null && !empty announcements}">
                                                <c:forEach var="announcement" items="${announcements}">
                                                    <tr>
                                                        <td>
                                                            <input type="checkbox" class="row-checkbox" value="${announcement.announcementId}" onchange="updateSelectedCount()">
                                                        </td>
                                                        <td>${announcement.announcementId}</td>
                                                        <td>${announcement.title}</td>
                                                        <td>
                                                            <c:choose>
                                                                <c:when test="${fn:length(announcement.content) > 50}">
                                                                    ${fn:substring(announcement.content, 0, 50)}...
                                                                </c:when>
                                                                <c:otherwise>
                                                                    ${announcement.content}
                                                                </c:otherwise>
                                                            </c:choose>
                                                        </td>
                                                        <td>
                                                            <c:choose>
                                                                <c:when test="${announcement.type == 0}">
                                                                    <span class="badge bg-primary">用户公告</span>
                                                                </c:when>
                                                                <c:when test="${announcement.type == 1}">
                                                                    <span class="badge bg-success">商家公告</span>
                                                                </c:when>
                                                                <c:otherwise>
                                                                    <span class="badge bg-secondary">未知</span>
                                                                </c:otherwise>
                                                            </c:choose>
                                                        </td>
                                                        <td>
                                                            <c:choose>
                                                                <c:when test="${announcement.status == 1}">
                                                                    <span class="badge bg-success">显示</span>
                                                                </c:when>
                                                                <c:otherwise>
                                                                    <span class="badge bg-secondary">隐藏</span>
                                                                </c:otherwise>
                                                            </c:choose>
                                                        </td>
                                                        <td><fmt:formatDate value="${announcement.createTime}" pattern="yyyy-MM-dd HH:mm"/></td>
                                                        <td><fmt:formatDate value="${announcement.updateTime}" pattern="yyyy-MM-dd HH:mm"/></td>
                                                        <td>
                                                            <button type="button" class="btn btn-sm btn-primary" 
                                                                    data-announcement-id="${announcement.announcementId}"
                                                                    data-title="${fn:escapeXml(announcement.title)}"
                                                                    data-content="${fn:escapeXml(announcement.content)}"
                                                                    data-type="${announcement.type}"
                                                                    data-status="${announcement.status}"
                                                                    onclick="openEditModalFromButton(this)">修改</button>
                                                            <button type="button" class="btn btn-sm btn-danger" 
                                                                    data-announcement-id="${announcement.announcementId}"
                                                                    onclick="deleteAnnouncementFromButton(this)">删除</button>
                                                        </td>
                                                    </tr>
                                                </c:forEach>
                                            </c:when>
                                            <c:otherwise>
                                                <tr>
                                                    <td colspan="9" class="text-center text-muted">暂无公告数据</td>
                                                </tr>
                                            </c:otherwise>
                                        </c:choose>
                                    </tbody>
                                </table>
                            </div>
                            
                            <!-- 分页 -->
                            <c:if test="${totalPages > 0}">
                                <nav aria-label="公告分页">
                                    <ul class="pagination justify-content-center">
                                        <li class="page-item ${page == 1 ? 'disabled' : ''}">
                                            <a class="page-link" href="${pageContext.request.contextPath}/admin/announcement?page=${page - 1}<c:if test='${title != null && !empty title}'>&title=${title}</c:if><c:if test='${content != null && !empty content}'>&content=${content}</c:if><c:if test='${type != null && !empty type}'>&type=${type}</c:if>">上一页</a>
                                        </li>
                                        <c:forEach var="i" begin="1" end="${totalPages}">
                                            <li class="page-item ${page == i ? 'active' : ''}">
                                                <a class="page-link" href="${pageContext.request.contextPath}/admin/announcement?page=${i}<c:if test='${title != null && !empty title}'>&title=${title}</c:if><c:if test='${content != null && !empty content}'>&content=${content}</c:if><c:if test='${type != null && !empty type}'>&type=${type}</c:if>">${i}</a>
                                            </li>
                                        </c:forEach>
                                        <li class="page-item ${page == totalPages ? 'disabled' : ''}">
                                            <a class="page-link" href="${pageContext.request.contextPath}/admin/announcement?page=${page + 1}<c:if test='${title != null && !empty title}'>&title=${title}</c:if><c:if test='${content != null && !empty content}'>&content=${content}</c:if><c:if test='${type != null && !empty type}'>&type=${type}</c:if>">下一页</a>
                                        </li>
                                    </ul>
                                </nav>
                                <div class="text-center text-muted">
                                    共 ${totalCount} 条记录，第 ${page}/${totalPages} 页
                                </div>
                            </c:if>
                        </div>
                    </div>
                </div>
            </main>
        </div>
    </div>
    
    <!-- 添加/编辑公告模态框 -->
    <div class="modal fade" id="announcementModal" tabindex="-1" aria-labelledby="announcementModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header bg-dark text-white">
                    <h5 class="modal-title" id="announcementModalLabel">添加公告</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="announcementForm">
                        <input type="hidden" id="announcementId" name="announcementId">
                        
                        <div class="mb-3">
                            <label for="title" class="form-label">标题 <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="title" name="title" required>
                        </div>
                        
                        <div class="mb-3">
                            <label for="content" class="form-label">内容 <span class="text-danger">*</span></label>
                            <textarea class="form-control" id="content" name="content" rows="5" required></textarea>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="type" class="form-label">类型 <span class="text-danger">*</span></label>
                                <select class="form-select" id="type" name="type" required>
                                    <option value="">请选择类型</option>
                                    <option value="0">用户公告</option>
                                    <option value="1">商家公告</option>
                                </select>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="status" class="form-label">状态</label>
                                <select class="form-select" id="status" name="status">
                                    <option value="1">显示</option>
                                    <option value="0">隐藏</option>
                                </select>
                            </div>
                        </div>
                        
                        <div class="alert alert-danger d-none" id="announcementError"></div>
                        <div class="alert alert-success d-none" id="announcementSuccess"></div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-dark" id="submitAnnouncementBtn" onclick="submitAnnouncement()">保存</button>
                </div>
            </div>
        </div>
    </div>
    
    <script src="${pageContext.request.contextPath}/js/bootstrap.bundle.min.js"></script>
    <script>
        let announcementModal = null;
        
        // 初始化模态框
        document.addEventListener('DOMContentLoaded', function() {
            announcementModal = new bootstrap.Modal(document.getElementById('announcementModal'));
        });
        
        // 打开添加模态框
        function openAddModal() {
            document.getElementById('announcementModalLabel').textContent = '添加公告';
            document.getElementById('announcementId').value = '';
            document.getElementById('title').value = '';
            document.getElementById('content').value = '';
            document.getElementById('type').value = '';
            document.getElementById('status').value = '1';
            
            // 清除验证状态
            document.getElementById('title').classList.remove('is-invalid');
            document.getElementById('content').classList.remove('is-invalid');
            document.getElementById('type').classList.remove('is-invalid');
            
            document.getElementById('announcementError').classList.add('d-none');
            document.getElementById('announcementSuccess').classList.add('d-none');
            
            announcementModal.show();
        }
        
        // 打开编辑模态框（从按钮获取数据）
        function openEditModalFromButton(button) {
            const announcementId = button.getAttribute('data-announcement-id');
            const title = button.getAttribute('data-title');
            const content = button.getAttribute('data-content');
            const type = button.getAttribute('data-type');
            const status = button.getAttribute('data-status');
            openEditModal(announcementId, title, content, type, status);
        }
        
        // 打开编辑模态框
        function openEditModal(announcementId, title, content, type, status) {
            document.getElementById('announcementModalLabel').textContent = '修改公告';
            document.getElementById('announcementId').value = announcementId;
            document.getElementById('title').value = title;
            document.getElementById('content').value = content;
            document.getElementById('type').value = type;
            document.getElementById('status').value = status;
            
            // 清除验证状态
            document.getElementById('title').classList.remove('is-invalid');
            document.getElementById('content').classList.remove('is-invalid');
            document.getElementById('type').classList.remove('is-invalid');
            
            document.getElementById('announcementError').classList.add('d-none');
            document.getElementById('announcementSuccess').classList.add('d-none');
            
            announcementModal.show();
        }
        
        // 提交公告
        function submitAnnouncement() {
            const announcementId = document.getElementById('announcementId').value.trim();
            const title = document.getElementById('title').value.trim();
            const content = document.getElementById('content').value.trim();
            const type = document.getElementById('type').value;
            const status = document.getElementById('status').value;
            
            // 清除之前的错误状态
            document.getElementById('title').classList.remove('is-invalid');
            document.getElementById('content').classList.remove('is-invalid');
            document.getElementById('type').classList.remove('is-invalid');
            
            const errors = [];
            
            // 验证标题
            if (!title) {
                errors.push('标题');
                document.getElementById('title').classList.add('is-invalid');
            }
            
            // 验证内容
            if (!content) {
                errors.push('内容');
                document.getElementById('content').classList.add('is-invalid');
            }
            
            // 验证类型
            if (!type) {
                errors.push('类型');
                document.getElementById('type').classList.add('is-invalid');
            }
            
            // 如果有错误，显示错误信息
            if (errors.length > 0) {
                showError('请检查以下字段：' + errors.join('、'));
                return;
            }
            
            const params = new URLSearchParams();
            if (announcementId) {
                params.append('action', 'update');
                params.append('announcementId', announcementId);
            } else {
                params.append('action', 'add');
            }
            params.append('title', title);
            params.append('content', content);
            params.append('type', type);
            params.append('status', status);
            
            const submitBtn = document.getElementById('submitAnnouncementBtn');
            submitBtn.disabled = true;
            submitBtn.textContent = '保存中...';
            
            document.getElementById('announcementError').classList.add('d-none');
            document.getElementById('announcementSuccess').classList.add('d-none');
            
            fetch('${pageContext.request.contextPath}/admin/announcement', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
                },
                body: params.toString()
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showSuccess(data.message);
                    setTimeout(function() {
                        announcementModal.hide();
                        location.reload();
                    }, 1500);
                } else {
                    showError(data.message || '操作失败');
                    submitBtn.disabled = false;
                    submitBtn.textContent = '保存';
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showError('操作失败，请重试');
                submitBtn.disabled = false;
                submitBtn.textContent = '保存';
            });
        }
        
        // 删除公告（从按钮获取ID）
        function deleteAnnouncementFromButton(button) {
            const announcementId = button.getAttribute('data-announcement-id');
            deleteAnnouncement(announcementId);
        }
        
        // 删除公告
        function deleteAnnouncement(announcementId) {
            if (!confirm('确定要删除这条公告吗？')) {
                return;
            }
            
            const params = new URLSearchParams();
            params.append('action', 'delete');
            params.append('announcementId', announcementId);
            
            fetch('${pageContext.request.contextPath}/admin/announcement', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
                },
                body: params.toString()
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert(data.message);
                    location.reload();
                } else {
                    alert(data.message || '删除失败');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('删除失败，请重试');
            });
        }
        
        function showError(message) {
            const errorDiv = document.getElementById('announcementError');
            errorDiv.textContent = message;
            errorDiv.classList.remove('d-none');
        }
        
        function showSuccess(message) {
            const successDiv = document.getElementById('announcementSuccess');
            successDiv.textContent = message;
            successDiv.classList.remove('d-none');
        }
        
        // 全选/取消全选
        function toggleSelectAll() {
            const selectAll = document.getElementById('selectAll');
            const checkboxes = document.querySelectorAll('.row-checkbox');
            checkboxes.forEach(checkbox => {
                checkbox.checked = selectAll.checked;
            });
            updateSelectedCount();
        }
        
        // 更新选中数量
        function updateSelectedCount() {
            const checkboxes = document.querySelectorAll('.row-checkbox:checked');
            const count = checkboxes.length;
            document.getElementById('selectedCount').textContent = count;
            document.getElementById('batchDeleteBtn').disabled = count === 0;
            
            // 更新全选状态
            const allCheckboxes = document.querySelectorAll('.row-checkbox');
            const selectAll = document.getElementById('selectAll');
            if (allCheckboxes.length === 0) {
                selectAll.checked = false;
                selectAll.indeterminate = false;
            } else if (count === allCheckboxes.length) {
                selectAll.checked = true;
                selectAll.indeterminate = false;
            } else if (count > 0) {
                selectAll.checked = false;
                selectAll.indeterminate = true;
            } else {
                selectAll.checked = false;
                selectAll.indeterminate = false;
            }
        }
        
        // 批量删除
        function batchDelete() {
            const checkboxes = document.querySelectorAll('.row-checkbox:checked');
            if (checkboxes.length === 0) {
                alert('请选择要删除的公告');
                return;
            }
            
            const announcementIds = Array.from(checkboxes).map(cb => cb.value);
            if (!confirm('确定要删除选中的 ' + announcementIds.length + ' 个公告吗？此操作不可恢复！')) {
                return;
            }
            
            const params = new URLSearchParams();
            params.append('action', 'batchDelete');
            announcementIds.forEach(id => {
                params.append('announcementIds[]', id);
            });
            
            const batchDeleteBtn = document.getElementById('batchDeleteBtn');
            batchDeleteBtn.disabled = true;
            batchDeleteBtn.textContent = '删除中...';
            
            fetch('${pageContext.request.contextPath}/admin/announcement', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
                },
                body: params.toString()
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert(data.message);
                    location.reload();
                } else {
                    alert(data.message || '删除失败');
                    batchDeleteBtn.disabled = false;
                    batchDeleteBtn.textContent = '批量删除';
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('删除失败，请重试');
                batchDeleteBtn.disabled = false;
                batchDeleteBtn.textContent = '批量删除';
            });
        }
        
        // 初始化选中数量
        document.addEventListener('DOMContentLoaded', function() {
            updateSelectedCount();
        });
    </script>
</body>
</html>

